<template>
  <div v-loading="loading">
    <el-row :gutter="20">
      <el-col :span="10">
        <div class="grid-content bg-purple">
          <el-form
            :model="addForm"
            ref="addForm"
            :rules="addRules"
            label-width="120px"
          >
            <el-form-item :label="$t('title')" prop="title">
              <el-input v-model="addForm.title"></el-input>
            </el-form-item>
            <el-form-item :label="$t('thumb')" prop="thumb">
              <crop-upload-url
                :width="200"
                :height="300"
                :file-url.sync="addForm.thumb"
                img-format="png"
              >
              </crop-upload-url>
            </el-form-item>
            <el-form-item label="图集" prop="image_list">
              <multiple-image-title :value="addForm.image_list"></multiple-image-title>
            </el-form-item>
            <el-form-item :label="$t('province')" prop="province">
              <province-edit-select
                @changeProvince="changeProvince"
                :nowValue.sync="addForm.province_adcode"
              ></province-edit-select>
            </el-form-item>
            <el-form-item :label="$t('diocese_id')" prop="diocese_id">
              <diocese-select
                :provinceAdcode="addForm.province_adcode"
                :nowValue.sync="addForm.diocese_id"
              ></diocese-select>
            </el-form-item>
            <el-form-item :label="$t('city')" prop="city">
              <el-input v-model="addForm.city" readonly></el-input>
            </el-form-item>
            <el-form-item :label="$t('district')" prop="district">
              <el-input v-model="addForm.district" readonly></el-input>
            </el-form-item>
            <el-form-item :label="$t('address')" prop="address">
              <el-input v-model="addForm.address"></el-input>
            </el-form-item>
            <el-form-item :label="$t('lng')" prop="lng">
              <el-input v-model="addForm.lng" readonly></el-input>
            </el-form-item>
            <el-form-item :label="$t('lat')" prop="lat">
              <el-input v-model="addForm.lat" readonly></el-input>
            </el-form-item>
            <el-form-item :label="$t('status')" prop="status">
              <el-switch
                v-model="addForm.status"
                active-value="1"
                inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="grid-content bg-purple">
          <div style="margin-bottom: 10px">
            <el-input
              placeholder="请输入地址"
              class="input-with-select"
              v-model="address"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchAddress"
              ></el-button>
            </el-input>
          </div>
          <div id="container"></div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <vue-neditor-wrap
            v-model="addForm.content"
            :config="editorConfig"
            :destroy="false"
            @ready="ready"
          ></vue-neditor-wrap>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <div class="grid-content bg-purple">
          <div slot="footer" class="dialog-footer">
            <el-button>{{ $t("cancel") }}</el-button>
            <el-button type="primary" @click="handleEditParish">{{
              $t("confirm")
            }}</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import notify from "../../../libs/notify";
import { getParishData, addParish, updateParish } from "../../../api/parish";
import VueNeditorWrap from "vue-neditor-wrap";
import DioceseSelect from "../../../components/Select/Diocese";
import ProvinceEditSelect from "../../../components/Select/ProvinceEdit";
import CropUploadUrl from "../../../components/CropUpload/CropUploadUrl";
import MultipleImageTitle from '../../../components/Webuploader/MultipleImageTitle';
export default {
  name: "adminParishEdit",
  components: {
    VueNeditorWrap,
    DioceseSelect,
    CropUploadUrl,
    ProvinceEditSelect,
    MultipleImageTitle
  },
  data: () => ({
    loading: true,
    loaded: { amap: false, editor: false, vue: false },
    addForm: {
      address: "",
      city: "",
      city_adcode: "",
      content: "",
      diocese_id: "",
      district: "",
      district_adcode: "",
      lat: "",
      lng: "",
      province: "",
      province_adcode: "",
      status: 0,
      title: "",
      thumb: "",
      image_list:[]
    },
    address: "",
    map: { AMap: null, map: null, marker: null, geocoder: null },
    addRules: {
      title: [{ required: true, message: "必须填写" }],
      diocese_id: [{ required: true, message: "必须填写" }],
      lng: [{ required: true, message: "必须填写" }],
      lat: [{ required: true, message: "必须填写" }],
    },
    editorConfig: {
      // 如果需要上传功能,找后端小伙伴要服务器接口地址
      serverUrl: "/upload",
      // 你的UEditor资源存放的路径,相对于打包后的index.html
      UEDITOR_HOME_URL: "/neditor/",
      // 编辑器不自动被内容撑高
      autoHeightEnabled: false,
      // 初始容器高度
      initialFrameHeight: 240,
      // 初始容器宽度
      initialFrameWidth: "100%",
      // 关闭自动保存
      enableAutoSave: false,
      compress: {
        width: 1000,
        height: 1000,
        // 图片质量，只有type为`image/jpeg`的时候才有效。
        quality: 90,
        // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
        allowMagnify: false,
        // 是否允许裁剪。
        crop: false,
        // 是否保留头部meta信息。
        preserveHeaders: true,
        // 如果发现压缩后文件大小比原来还大，则使用原来图片
        // 此属性可能会影响图片自动纠正功能
        noCompressIfLarger: false,
        // 单位字节，如果图片大小小于此值，不会采用压缩。
        compressSize: 0,
      },
    },
  }),
  created() {
    AMapLoader.load({
      //首次调用 load
      key: this.$config.amap.key, //首次load key为必填
      version: "2.0",
      plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.Geocoder"],
    })
      .then((AMap) => {
        //AMap加载成功检测
        this.loaded.amap = true;
        this.setLoading();
        this.map.AMap = AMap;
        //生成工具条
        let toolBar = new AMap.ToolBar({
          position: {
            top: "10px",
            right: "10px",
          },
        });
        //初始化地理编码
        this.map.geocoder = new AMap.Geocoder();
        //初始化map
        let map = (this.map.map = new AMap.Map("container", {
          zoom: 10,
        }));
        //初始化（生成）覆盖物
        this.initMarker();
        map.addControl(toolBar);
        let that = this;
        map.on("click", function (e) {
          that.addMarker(e.lnglat);
          that.setForm(e.lnglat);
        });
      })
      .catch((e) => {
        console.error(e);
      });
    //created加载成功检测
    this.loaded.vue = true;
    this.setLoading();
  },
  methods: {
    //异步加载成功检测执行方法
    async setLoading() {
      if (
        this.loaded.vue == true &&
        this.loaded.amap == true &&
        this.loaded.editor == true
      ) {
        this.loading = false;
        const id = this.$route.params.id;
        if (id == undefined) return;
        let response = await getParishData(id);
        if (response.status == 200 && response.data) {
          let lnglat = new this.map.AMap.LngLat(
            response.data.lng,
            response.data.lat
          );
          //设置地图主心点
          this.map.map.setCenter(lnglat);
          //添加覆盖物
          this.addMarker(lnglat);
          for (let key in response.data) {
            if (typeof this.addForm[key] != "undefined") {
              this.addForm[key] = response.data[key];
            }
          }
          this.addForm.status = this.addForm.status.toString();
        }
      }
    },
    ready() {
      //ueditor编辑器加载成功检测
      this.loaded.editor = true;
      this.setLoading();
    },
    handleEditParish() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          let id = this.$route.params.id;
          if (id == undefined) {
            addParish(this.addForm).then((response) => {
              notify.createSuccessNew(this, () => {
                this.$router.push({ name: "adminParishIndex" });
              });
            });
          } else {
            updateParish(id, this.addForm).then((response) => {
              notify.editSuccessNew(this, () => {
                this.$router.push({ name: "adminParishIndex" });
              });
            });
          }
        } else {
          return false;
        }
      });
    },
    //初始化覆盖物
    initMarker() {
      let AMap = this.map.AMap;
      let icon = new AMap.Icon({
        size: new AMap.Size(50, 60), // 图标尺寸
        image: "/images/church.svg", // Icon的图像
        imageSize: new AMap.Size(50, 60), // 根据所设置的大小拉伸或压缩图片
      });
      let marker = this.map.marker = new AMap.Marker({
        anchor : 'bottom-center',
        draggable : true
        // icon: icon,
        // offset: new AMap.Pixel(-25, -25),
      });
      marker.on('dragend',(e)=>{
        console.log('dragend',e);
        this.setForm(e.lnglat);
      })
      return marker;
    },
    //添加或移动覆盖物
    addMarker(LngLat) {
      this.map.marker.setPosition(LngLat);
      this.map.map.add(this.map.marker);
      this.map.map.setFitView();
    },
    setForm(lnglat) {
      //地址查询
      this.map.geocoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          let address = result.regeocode.addressComponent;
          let str = address.adcode;
          this.addForm.province_adcode = str.substring(0, 2).padEnd(6, 0);
          this.addForm.district_adcode = str;
          this.addForm.city_adcode = str.substring(0, 4).padEnd(6, 0);
          this.addForm.lng = lnglat.lng;
          this.addForm.lat = lnglat.lat;
          this.addForm.province = address.province;
          this.addForm.city = address.city;
          this.addForm.district = address.district;
          this.addForm.address =
            address.township + address.street + address.streetNumber;
          this.addForm.diocese_id = "";
        } else {
          log.error("根据经纬度查询地址失败");
        }
      });
    },
    //省手动更改
    changeProvince($event) {
      let [lng, lat] = $event.center.split(",");
      this.map.map.clearMap();
      let lnglat = new this.map.AMap.LngLat(lng, lat);
      this.map.map.setCenter(lnglat);
      this.map.map.setZoom(10);
      this.addForm.city = "";
      this.addForm.district = "";
      this.addForm.lng = "";
      this.addForm.lat = "";
      this.addForm.address = "";
      this.address = "";
      this.addForm.diocese_id = "";
    },
    //地址搜索
    searchAddress() {
      if (!this.address) return;
      this.map.geocoder.getLocation(this.address, (status, result) => {
        console.log(result);
        if (status === "complete" && result.geocodes.length) {
          let lnglat = result.geocodes[0].location;
          this.addMarker(lnglat);
          this.setForm(lnglat);
        } else {
          this.$message.error("地址查询失败");
        }
      });
    },
  },
};
</script>
<style scoped>
#container {
  width: 100%;
  height: 450px;
}
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
</style>
